/**
 * 
 */
package dt.inlee.system.action;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.googlecode.sslplugin.annotation.Secured;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import com.sjb.common.util.MD5;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.util.LogUtil;
import dt.inlee.common.util.SystemResourceUtil;
import dt.inlee.domain.SysMenu;
import dt.inlee.domain.SysOrganization;
import dt.inlee.domain.SysUser;
import dt.inlee.system.service.SysUserService;
import dt.inlee.system.vo.SysUserLoginBean;

/**
 * @功能说明：登录控制层
 * @作者： 赵欢欢，周红
 * @创建日期： 2010-5-7 @
 */
@SuppressWarnings("serial")
@Scope("prototype")
@Results({@Result(name = "success", location = "/client.jsp"), @Result(name = "input", location = "/login.jsp")})
@Controller("loginAction")
public class LoginAction extends ActionSupport {
    private static Logger logger = Logger.getLogger(LoginAction.class);
    @Autowired
    private SysUserService sysUserService;
    private SysUserLoginBean sysUserLoginBean;
    private String loginMessage;
    private boolean result = false;
    // 是否来至励生活
    private boolean isComeLife = false;
    // 是否进行手机验证码验证?
    private boolean mobileCode = false;

    public SysUserLoginBean getSysUserLoginBean() {
        return sysUserLoginBean;
    }

    public String getLoginMessage() {
        return loginMessage;
    }

    public void setLoginMessage(String loginMessage) {
        this.loginMessage = loginMessage;
    }

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public boolean isMobileCode() {
        return mobileCode;
    }

    public void setMobileCode(boolean mobileCode) {
        this.mobileCode = mobileCode;
    }

    @Validations(visitorFields = {@VisitorFieldValidator(message = "test", fieldName = "model", appendPrefix = false)})
    public void setSysUserLoginBean(SysUserLoginBean sysUserLoginBean) {
        this.sysUserLoginBean = sysUserLoginBean;
    }

    /**
     * testlogin说明是物业增值平台直接调用登录
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "testlogin", results = {@Result(name = "success", location = "/sso.jsp")})
    public String testlogin() throws FrameworkException, Exception {
        this.isComeLife = true;
        this.result = logins();
        return SUCCESS;
    }

    /**
     * 普通方式登录接口
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "login", interceptorRefs = {@InterceptorRef("privilegeStack"), @InterceptorRef("reLogin")}, results = {@Result(type = "json", params = {
            "excludeNullProperties", "true", "includeProperties", "result,loginMessage,mobileCode"})})
    public String login() throws FrameworkException, Exception {
        this.result = logins();
        return SUCCESS;
    }

    /**
     * SSL方式登录接口
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "loginSSL", interceptorRefs = {@InterceptorRef("privilegeStack"), @InterceptorRef("secure"),
            @InterceptorRef("reLogin")}, results = {@Result(type = "json", params = {"excludeNullProperties", "true",
            "includeProperties", "result,loginMessage,mobileCode"})})
    @Secured
    public String loginSSL() throws FrameworkException, Exception {
        this.result = logins();
        return SUCCESS;
    }

    /**
     * 用户退出
     * 
     * @return
     * @throws FrameworkException
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @Action(value = "exitLogin")
    public String exitLogin() throws FrameworkException, Exception {
        logger.debug("LoginAction exitLogin()");
        // 登陆用户信息
        SysUserLoginBean loginUser =
                (SysUserLoginBean) ActionContext.getContext().getSession().get(CommonConstant.SESSION_USER);
        LogUtil.getInstance().logoutExecution();
        // 清空在线列表
        if (ActionContext.getContext().getSession().containsKey(CommonConstant.SESSION_USER)) {
            ActionContext.getContext().getSession().remove(CommonConstant.SESSION_USER);
        }
        ServletContext sc = ServletActionContext.getServletContext();
        Map<String, String> onlineUser = Collections.emptyMap();
        onlineUser = (Map<String, String>) sc.getAttribute(CommonConstant.SERVLETCONTEXT_ONLINE_USER);
        logger.debug("LoginAction onlineUser() remove befor:" + onlineUser);
        if (!BaseUtil.isEmpty(loginUser) && !BaseUtil.isEmpty(onlineUser)
                && onlineUser.containsKey(loginUser.getUserName())) {
            onlineUser.remove(loginUser.getUserName());
        }
        logger.debug("LoginAction onlineUser() remove after:" + onlineUser);
        sc.setAttribute(CommonConstant.SERVLETCONTEXT_ONLINE_USER, onlineUser);
        return LOGIN;
    }

    /**
     * 登陆通用方法,为普通登陆和ssl登陆公用
     * 
     * @return
     * @throws FrameworkException
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private boolean logins() throws FrameworkException, Exception {
        String verificationStatus = SystemResourceUtil.getInstance().getResourceAsString("VERIFICATION_STATUS");
        verificationStatus = "";
        if (!BaseUtil.isEmpty(verificationStatus) && verificationStatus.equalsIgnoreCase("enabled")) {
            // 客户需求去掉验证码
            String verification = (String) ServletActionContext.getRequest().getSession().getAttribute("verification");
            if (BaseUtil.isEmpty(verification)) {
                this.loginMessage = "验证码过期,请再次登录!";
                return false;
            } else {
                if (BaseUtil.isEmpty(sysUserLoginBean.getVerification())) {
                    this.loginMessage = "请输入验证码!";
                    return false;
                } else if (!verification.equals(sysUserLoginBean.getVerification())) {
                    this.loginMessage = "输入验证码不正确,请重新输入!";
                    return false;
                }
            }
        }
        sysUserLoginBean.setUserName(sysUserLoginBean.getUserName() + "@"
                + sysUserLoginBean.getSimpleCode().toUpperCase());
        String md5Password = "";
        // 如果来至励生活就不需要md5转译
        if (isComeLife) {
            md5Password = sysUserLoginBean.getPassword();
        } else {
            md5Password = MD5.getVsMd5(sysUserLoginBean.getPassword());
        }
        Map<String, SysUser> loginStatus = this.sysUserService.login(sysUserLoginBean.getUserName(), md5Password);
        if (!BaseUtil.isEmpty(loginStatus)) {
            String status = loginStatus.keySet().iterator().next();
            SysUser sysUser = loginStatus.get(status);
            if (!sysUser.getDisabled()) {
                this.loginMessage = "该用户已禁用,不能登录!";
                return false;
            } else if ("startError".equalsIgnoreCase(status)) {
                this.loginMessage = "生效开始日期大于当前日期,不能登录!";
                return false;
            } else if ("endError".equalsIgnoreCase(status)) {
                this.loginMessage = "生效结束日期小于当前日期,不能登录!";
                return false;
            } else if ("betweenError".equalsIgnoreCase(status)) {
                this.loginMessage = "生效日期已失效,不能登录!";
                return false;
            }

            BeanUtils.copyProperties(sysUser, sysUserLoginBean);
            sysUserLoginBean.setMobileCode(sysUser.getMobile());
            List<SysMenu> sysMenus = sysUserService.queryRightsMenus(sysUser.getId());
            sysUserLoginBean.setRealName(sysUser.getRealName());
            List<SysOrganization> sysOrgs = sysUser.getSysOrganizations();
            if (!BaseUtil.isEmpty(sysOrgs) && sysOrgs.size() > 0) {

                sysUserLoginBean.setOrganizationId(sysOrgs.get(0).getId());
                sysUserLoginBean.setOrganizationName(sysOrgs.get(0).getName());
            }
            // 获取菜单
            sysUserLoginBean.setMenuList(sysMenus);
            // 登录人IP
            sysUserLoginBean.setIp(this.getRemortIP());
            // 将登录信息放入session
            ActionContext.getContext().getSession().put(CommonConstant.SESSION_USER, sysUserLoginBean);
            LogUtil.getInstance().loginExecution();
            Map<String, String> users =
                    (Map<String, String>) ServletActionContext.getServletContext().getAttribute(
                            CommonConstant.SERVLETCONTEXT_ONLINE_USER);
            if (users == null) {
                users = new HashMap<String, String>();
            }
            users.put(sysUserLoginBean.getUserName(), ServletActionContext.getRequest().getSession().getId());
            ServletActionContext.getServletContext().setAttribute(CommonConstant.SERVLETCONTEXT_ONLINE_USER, users);
            if (sysUser.isIsvalidsm() == 0 ? false : true) {
                this.mobileCode = true;
                this.loginMessage = "请注意接收短信验证码,进行再次验证登录!";
            } else {
                this.loginMessage = "登录成功!";
            }
            return true;
        } else {
            this.loginMessage = "用户名或密码错误!";
            return false;
        }
    }

    @SuppressWarnings("unused")
    private String filterDangerString(String value) {
        if (value == null) {
            return null;
        }
        value = value.replaceAll("\\|", "");
        value = value.replaceAll("&", "&amp;");
        value = value.replaceAll(";", "");
        value = value.replaceAll("@", "");
        value = value.replaceAll("'", "");
        value = value.replaceAll("\"", "");
        value = value.replaceAll("\\'", "");
        value = value.replaceAll("\\\"", "");
        value = value.replaceAll("<", "&lt;");
        value = value.replaceAll(">", "&gt;");
        value = value.replaceAll("\\(", "");
        value = value.replaceAll("\\)", "");
        value = value.replaceAll("\\+", "");
        value = value.replaceAll("\r", "");
        value = value.replaceAll("\n", "");
        value = value.replaceAll("script", "");
        value = value.replaceAll("%27", "");
        value = value.replaceAll("%22", "");
        value = value.replaceAll("%3E", "");
        value = value.replaceAll("%3C", "");
        value = value.replaceAll("%3D", "");
        value = value.replaceAll("%2F", "");
        return value;
    }

    private String getRemortIP() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String ip = addr.getHostAddress();// 获得本机IP
        return ip;
    }
}
